package com.jstyle.jclifexd.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.AboutUsActivity;
import com.jstyle.jclifexd.activity.ActivitiesActivity;
import com.jstyle.jclifexd.activity.AutoHeartActivity;
import com.jstyle.jclifexd.activity.BPCalibrationActivity;
import com.jstyle.jclifexd.activity.BindDeviceActivity;
import com.jstyle.jclifexd.activity.BindDeviceListActivity;
import com.jstyle.jclifexd.activity.DeviceSettingActivity;
import com.jstyle.jclifexd.activity.FeedBackActivity;
import com.jstyle.jclifexd.activity.FileUpdateActivity;
import com.jstyle.jclifexd.activity.GoalActivity;
import com.jstyle.jclifexd.activity.LoginActivity;
import com.jstyle.jclifexd.activity.NotificationlistActivity;
import com.jstyle.jclifexd.activity.RankActivity;
import com.jstyle.jclifexd.activity.TeamperformanceActivity;
import com.jstyle.jclifexd.activity.ThirdDataActivity;
import com.jstyle.jclifexd.activity.UserInfoActivity;
import com.jstyle.jclifexd.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclifexd.adapter.SettingAdapter;
import com.jstyle.jclifexd.ble.BleManager;
import com.jstyle.jclifexd.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclifexd.daoManager.GpsDataDaoManager;
import com.jstyle.jclifexd.daoManager.HealthDataDaoManager;
import com.jstyle.jclifexd.daoManager.HeartDataDaoManager;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.daoManager.SleepDataDaoManager;
import com.jstyle.jclifexd.daoManager.StepDataDaoManager;
import com.jstyle.jclifexd.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.BindDeviceInfo;
import com.jstyle.jclifexd.model.QueryUserStatemsg;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.GlobalConst;
import com.jstyle.jclifexd.utils.ImageUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.HeadCircleView;
import com.jstyle.jclifexd.view.TipsDialog;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SettingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SettingFragment extends BaseFragment implements RecyclerViewBaseAdapter.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM_Version = "param1";
    private static final String ARG_PARAM_BATTERY = "param2";
    @BindView(R.id.RecyclerView)
    RecyclerView RecyclerView_setting;
    Unbinder unbinder;
    @BindArray(R.array.array_setting)
    String[] arraySetting;
    @BindView(R.id.bt_setting_activity)
    Button btSettingActivity;
    @BindView(R.id.bt_setting_rank)
    Button btSettingRank;
    @BindView(R.id.bt_setting_status)
    Button btSettingStatus;
    @BindView(R.id.bt_group_rank)
    Button btGroupRank;
    @BindView(R.id.iv_setting_icon)
    ImageView ivSettingIcon;
    @BindView(R.id.bt_setting_name)
    Button btSettingName;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private SettingAdapter settingAdapter;
    private String updateFilePath;
    private boolean isNeedUpdate;
    private String otaPath;
    private String deviceVersion;

    public SettingFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SettingFragment newInstance(String param1, String param2) {
        SettingFragment fragment = new SettingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM_Version, param1);
        args.putString(ARG_PARAM_BATTERY, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM_Version);
            mParam2 = getArguments().getString(ARG_PARAM_BATTERY);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        //  sendData(SendCmdState.READ_DEVICE_BATTERY);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        settingAdapter = new SettingAdapter(Arrays.asList(arraySetting));
        settingAdapter.setOnItemClickListener(this);
        RecyclerView_setting.setAdapter(settingAdapter);
        RecyclerView_setting.setLayoutManager(linearLayoutManager);
        settingAdapter.setBattery(mParam2);
        if (mListener != null) mListener.readBatteryAndVersion();
    }

    // TODO: Rename method, update argument and hook method into UI event

    @Override
    public void onResume() {
        super.onResume();
        updateUserInfo();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    public void updateUserInfo() {
        if (!isAdded()) return;
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(NetWorkUtil.getUserId());
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(NetWorkUtil.getUserId());
            UserInfoDaoManager.insertUser(userInfo);
        }
        Uri iconUri = ImageUtils.getIconUri(getActivity(), userInfo.getUserId());
        String userName = userInfo.getName();
        Bitmap bmHead = ImageUtils.findHeadBitmap(getActivity(), iconUri);
        if(bmHead == null){
            if (ivSettingIcon == null) return;
            if(!TextUtils.isEmpty(userInfo.getIconPath())){
                Glide.with(getActivity())
                        .load(userInfo.getIconPath())
                        .diskCacheStrategy(DiskCacheStrategy.DATA) // 不使用磁盘缓存
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .error( R.drawable.user_icon)
                        .into(ivSettingIcon);
            }
        }else{
            HeadCircleView circleView = new HeadCircleView(bmHead);
            if (ivSettingIcon == null) return;
            ivSettingIcon.setImageDrawable(circleView);
        }

        if (TextUtils.isEmpty(userName)) userName = GlobalConst.KEY_DefaultName;
        btSettingName.setText(userName);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(int position) {
        if(Utils.isFastClick()){return;}
        switch (position) {
            case 0:
                String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
                List<BindDeviceInfo> bindDeviceInfoList = BindDeviceInfoDaoManager.queryAllData();
                startActivity(bindDeviceInfoList.size() == 0 ? BindDeviceActivity.class : BindDeviceListActivity.class);
                break;
            case 2:
                startActivity(UserInfoActivity.class);
                break;
            case 3:
                startActivity(GoalActivity.class);
                break;
            case 4:
                startActivity(AutoHeartActivity.class);
                break;
            case 5:
                startActivity(DeviceSettingActivity.class);
                break;
            case 6:
                startActivity(ThirdDataActivity.class);
                break;

            case 7:
                checkVersion();
                break;
            case 8:
                showResetDialog();
                break;
            case 9:
                startActivity(BPCalibrationActivity.class);
                break;
            case 11:
                startActivity(AboutUsActivity.class);
                //startActivity(ThirdDataActivity.class);
                break;
            case 12:
                startActivity(FeedBackActivity.class);
                break;
            case 13:
                exitLogin();
                break;
        }
    }

    private void exitLogin() {
        //   CsvUtils.createSleepCsvFile();
        getActivity().finish();
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, false);
        startActivity(LoginActivity.class);
    }

    private void checkVersion() {
        // showChargeDialog();

        if (BleManager.getInstance().isConnected()) {
            if (isNeedUpdate) {
                int battery = settingAdapter.getBattery();
                if (battery > 20) {
                    showUpdateDialog(updateFilePath, battery);
                } else {
                    showChargeDialog();
                }

            } else {
                showToast(getString(R.string.Latest_Version_Already));
            }
        } else {
            showToast(getString(R.string.Bluetooth_Disconnected));
        }

    }

    AlertDialog alertDialogCharge;

    private void showChargeDialog() {
        TipsDialog tipsDialog = new TipsDialog(getActivity(), R.style.jstyleDialog_style);
        tipsDialog.setTitle(getString(R.string.low_battery_title));
        tipsDialog.setContent(getString(R.string.Low_battery_caution_content));
        tipsDialog.setConfimText(getString(R.string.low_battery_ok));
        tipsDialog.setButtonCancelGone();
        tipsDialog.show();
//        if(alertDialogCharge==null){
//            alertDialogCharge=new AlertDialog.Builder(getActivity())
//                    .setTitle(getString(R.string.Low_battery_caution))
//                    .setMessage()
//                    .setPositiveButton(,null).create();
//        }
//        if(!alertDialogCharge.isShowing())alertDialogCharge.show();
    }

    private void showUpdateDialog(final String filePath, int batteryValue) {
        Intent intent = new Intent(getActivity(), FileUpdateActivity.class);
        intent.putExtra(FileUpdateActivity.key_url, filePath);
        intent.putExtra(FileUpdateActivity.key_version, deviceVersion);
        intent.putExtra(FileUpdateActivity.key_battery, batteryValue);
        startActivity(intent);
    }


    private String updateFileName = "firmware.zip";


    private void showResetDialog() {
        if (!BleManager.getInstance().isConnected()) {
            showToast(getString(R.string.Bluetooth_Disconnected));
            return;
        }
        TipsDialog tipsDialog = new TipsDialog(getActivity(), R.style.jstyleDialog_style);
        tipsDialog.setTipsConfimListener(new TipsDialog.TipsConfimListener() {
            @Override
            public void onConfim() {
                sendData(SendCmdState.SET_FACTORY);
            }
        });
        tipsDialog.show();

    }

    private void deleteAllData() {
        GpsDataDaoManager.deleteAll();
        HeartDataDaoManager.deleteAll();
        HealthDataDaoManager.deleteAll();
        PathRecordDaoManager.deleteAll();
        SleepDataDaoManager.deleteAll();
        StepDetailDataDaoManager.deleteAll();
        StepDataDaoManager.deleteAll();
    }

    @OnClick({R.id.bt_setting_activity, R.id.bt_setting_rank, R.id.bt_setting_status, R.id.bt_group_rank,R.id.iv_setting_icon
    ,R.id.info_notification})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.info_notification:
                startActivity(NotificationlistActivity.class);
                break;
            case R.id.bt_setting_activity:
                if(Utils.checkNetWork(getActivity())){
                    startActivity(ActivitiesActivity.class);
                }else{
                    showToast(getActivity().getString(R.string.Network_not_availa));
                }
                break;
            case R.id.bt_setting_rank:
                if(Utils.checkNetWork(getActivity())){
                    startActivity(RankActivity.class);
                }else{
                    showToast(getActivity().getString(R.string.Network_not_availa));
                }
                break;
            case R.id.bt_setting_status:
                break;
            case R.id.bt_group_rank:
                if(Utils.checkNetWork(getActivity())){
                    QueryUserState();
                }else{
                    showToast(getActivity().getString(R.string.Network_not_availa));
                }
                break;
            case R.id.iv_setting_icon:
                Log.i(TAG, "onViewClicked: ");
                startActivity(UserInfoActivity.class);
                break;

        }
    }


    private void QueryUserState(){
        Map<String,Object> map=new HashMap<>();
        map.put("uid",NetWorkUtil.getUserId());
        NetWorkUtil.getInstance().getJstyleApi().getqueryUserState(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<QueryUserStatemsg>() {
            @Override
            public void onSubscribe(Disposable d) {}
            @Override
            public void onNext(QueryUserStatemsg activitvtiesData) {
                Intent intent;
                if(activitvtiesData.getData().getState().equals("no")){//没有加入团队进入活动界面加团队
                     intent=new Intent(getActivity(),ActivitiesActivity.class);
                }else{
                   intent=new Intent(getActivity(),TeamperformanceActivity.class);
                }
                startActivity(intent);
            }
            @Override
            public void onError(Throwable e) { }
            @Override
            public void onComplete() { }
        });

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void readBatteryAndVersion();
    }

    private static final String TAG = "SettingFragment";

    public void updateBattery(String battery) {
        if (isAdded())
            settingAdapter.setBattery(battery);
        Log.i(TAG, "updateBattery: " + battery);
    }

    public void updateVersion(String updateFilePath, String version) {
        String versionCode = version.replace(".", "");
        this.updateFilePath = updateFilePath;
        deviceVersion = version;
//        settingAdapter.setBattery(battery);
//        Log.i(TAG, "updateBattery: "+battery);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (mListener != null) mListener.readBatteryAndVersion();
        }
    }


    public void changeUpdateStatus(boolean isNeedUpdate) {
        if (settingAdapter == null) return;
        this.isNeedUpdate = isNeedUpdate;
        settingAdapter.setNeedUpdate(isNeedUpdate);
    }

}
